package com.fyzk.activity.fragment;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.lottery.recommend_order.MyRecommendOrderBean;
import com.fyzk.activity.popupwindow.FollowDocumentaryPopupWindow;
import com.fyzk.adapter.BetDetailsAdapter;
import com.fyzk.base.BaseFragment;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.model.BluePrintDetailsViewModel;
import com.fyzk.net.Commands;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.TimeUtil;
import com.fyzk.view.widget.DividerItemDecoration;
import com.tyjc.lottery.R;

import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * 投注详情的fragment
 */
@ContentView(R.layout.fragment_bet_details)
public class BetDetailsFragment extends BaseFragment implements Observer<MyRecommendOrderBean> {
    @ViewInject(R.id.tv_describe)
    TextView mTvDescribe;
    @ViewInject(R.id.rv_bet_details)
    RecyclerView mRvBetDetails;
    @ViewInject(R.id.tv_cut_off_date)
    TextView mTvCutOffDate;
    @ViewInject(R.id.tv_made_the_documentary)
    TextView mTvMadeTheDocumentary;
    @ViewInject(R.id.tv_is_secrecy)
    TextView mTvIsSecrecy;
    @ViewInject(R.id.tv_pass_way)
    TextView mTvPassWay;
    @ViewInject(R.id.tv_brokerage)
    TextView mTvBrokerage;
    @ViewInject(R.id.iv_hot1)
    ImageView mIvHot1;
    @ViewInject(R.id.iv_hot2)
    ImageView mIvHot2;
    @ViewInject(R.id.iv_hot3)
    ImageView mIvHot3;
    @ViewInject(R.id.iv_lock)
    ImageView mInLock;
    @ViewInject(R.id.fl_bet_detail)
    FrameLayout mFlBetDetail;

    private MyRecommendOrderBean mInfo;
    private double followTotalAmount;//跟单总金额
    private int followTotalNumber;//跟单总人数

    private BetDetailsAdapter mBetDetailsAdapter;
    private LinearLayoutManager mBetDetailsManager;

    private BluePrintDetailsViewModel mBluePrintDetailsViewModel;

    private View betDetailHeader;

    private String mUserNo;

    public static BetDetailsFragment newInstance(MyRecommendOrderBean mInfo, String mUserNo) {
        Bundle args = new Bundle();
        args.putSerializable(IntentParamUtils.RECOMMENDINFOR, mInfo);
        args.putString(IntentParamUtils.USERNO, mUserNo);
        BetDetailsFragment fragment = new BetDetailsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null != getArguments()) {
            mInfo = (MyRecommendOrderBean) getArguments().getSerializable(IntentParamUtils.RECOMMENDINFOR);
            mUserNo = getArguments().getString(IntentParamUtils.USERNO);
        }
        return x.view().inject(this, inflater, container);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTvMadeTheDocumentary.setOnClickListener(this);
        mBluePrintDetailsViewModel = ViewModelProviders.of(getActivity()).get(BluePrintDetailsViewModel.class);
        mBluePrintDetailsViewModel.getBluePrintDetailsViewModel().observe(this, this);
        loadData(false, mInfo);
    }

    /**
     * 初始化数据
     *
     * @param mData
     */
    private void initViews(MyRecommendOrderBean mData) {
        mTvPassWay.setText(null == mData.getDetail() ? "" : mData.getDetail().getPlayName());
        //是否显示跟单金额。0显示，1不显示
        if (TextUtils.equals("1", mData.getIsShowAmt())) {
            mTvIsSecrecy.setText("保密");
        } else {
//            mTvIsSecrecy.setText(mData.getMultiple() + "米");
            mTvIsSecrecy.setText(new DecimalFormat("#0.00").format(followTotalAmount / 100) + "米");
        }
        mIvHot1.setVisibility(followTotalNumber >= 1 ? View.VISIBLE : View.GONE);
        mIvHot2.setVisibility(followTotalNumber >= 4 ? View.VISIBLE : View.GONE);
        mIvHot3.setVisibility(followTotalNumber >= 7 ? View.VISIBLE : View.GONE);
        mTvBrokerage.setText(mData.getProportions() + "%");
//        mTvFansNum.setText(mData.getPopularity());
        mTvCutOffDate.setText("截止时间：" + mData.getEndTime());
        mTvMadeTheDocumentary.setBackgroundResource(mData.getOrderResultStatus() == 5
                && System.currentTimeMillis() < TimeUtil.stringToLong(mData.getEndTime()) ?
                R.drawable.rr_with_btn_bg_yes :
                R.drawable.rr_with_btn_bg_yes_alpha50);
        mTvDescribe.setText(mData.getMemo());
        mBetDetailsManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mBetDetailsAdapter = new BetDetailsAdapter();
        mRvBetDetails.setLayoutManager(mBetDetailsManager);
        mBetDetailsAdapter.bindToRecyclerView(mRvBetDetails);
        DividerItemDecoration decoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        decoration.setDrawable(getResources().getDrawable(R.drawable.item_bet_details_divider));
        mRvBetDetails.addItemDecoration(decoration);
        betDetailHeader = getLayoutInflater().inflate(R.layout.item_bet_details_header, null);
        MyRecommendOrderBean.DetailBean mBetDetailsData = mData.getDetail();
        initBetDetails(mBetDetailsData, !isSelf() && (mBetDetailsData == null ||
                ((mData.getWay() == 2 && mData.getOrderResultStatus() == 5
                        && System.currentTimeMillis() <= TimeUtil.stringToLong(mData.getEndTime())))));
        mTvMadeTheDocumentary.setVisibility(isSelf() ? View.GONE : View.VISIBLE);
    }

    /**
     * 初始化跟单列表
     *
     * @param mBetDetailsData 跟单列表数据
     * @param mIsSecrecy      是否保密 0,不保密，其他 保密
     */
    private void initBetDetails(MyRecommendOrderBean.DetailBean mBetDetailsData, boolean mIsSecrecy) {
//        if (!isSelf() && (null == mBetDetailsData || 0 != mIsSecrecy)) {//保密
        if (mIsSecrecy) {//保密
            mFlBetDetail.setVisibility(View.GONE);
            mBetDetailsAdapter.removeHeaderView(betDetailHeader);
            mBetDetailsAdapter.setNewData(null);
            mInLock.setImageResource(R.drawable.icon_locked);
        } else if (null != mBetDetailsData) {//不保密
            mFlBetDetail.setVisibility(View.VISIBLE);
            List<MyRecommendOrderBean.DetailBean.RaceBetcodeBean> mRaceBetCodeData = mBetDetailsData.getRaceBetcode();
            mBetDetailsAdapter.removeAllHeaderView();
            mBetDetailsAdapter.addHeaderView(betDetailHeader);
            mBetDetailsAdapter.setNewData(mRaceBetCodeData);
            mInLock.setImageResource(R.drawable.icon_unlock);
        }
    }

    /**
     * 请求数据
     *
     * @param show  是否显示Loading
     * @param mData
     */
    private void loadData(boolean show, MyRecommendOrderBean mData) {
        JSONObject request_json = new JSONObject();
        try {
            followTotalAmount = mData.getFollowTotalAmount();
            followTotalNumber = mData.getFollowTotalNumber();
            request_json.put("recommendId", mData.getRecommendId());
            httpPostJson(CommandUtil.FINDRECOMMENDEDRANKUSETCSTYLE, Commands.FINDRECOMMENDEDRANKUSETCSTYLE, request_json,
                    show);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否是自己
     *
     * @return
     */
    private boolean isSelf() {
        return TextUtils.equals(MySharedPreferences.getInstance().getUserNo(), mUserNo);
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSETCSTYLE:
                MyRecommendOrderBean mData = JSON.parseObject(resultBean.getData(), MyRecommendOrderBean.class);
                initViews(mData);
                break;
        }
    }

    @Override
    public void onFailure(int requestCode, String errorcode, String msg) {
        super.onFailure(requestCode, errorcode, msg);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSETCSTYLE:
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode, String message) {
        super.onFailure(requestCode, message);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSETCSTYLE:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_made_the_documentary:
//                Intent intent = new Intent(getContext(), RecommendDetailActivity.class);
//                intent.putExtra(IntentParamUtils.RECOMMENDINFOR, mInfo);
//                startActivity(intent);
                showFollowDocumentaryPopup(mInfo);
                break;
        }
    }

    FollowDocumentaryPopupWindow followDocumentaryPopupWindow;

    /**
     * 展示跟单的弹窗
     *
     * @param item 跟单内容
     */
    private void showFollowDocumentaryPopup(MyRecommendOrderBean item) {
        if (null == item || !(item.getOrderResultStatus() == 5
                && System.currentTimeMillis() < TimeUtil.stringToLong(item.getEndTime()))) {
            showToast("已经截止");
            return;
        }
        if (isSelf()) {
            showToast("不能跟自己的单");
            return;
        }
        followDocumentaryPopupWindow = new FollowDocumentaryPopupWindow(getActivity(), item);
        followDocumentaryPopupWindow.showPopupWindow();
    }

    /**
     * 点击关注，进入登录界面，然后回来，重新请求数据。
     *
     * @param data
     */
    @Override
    public void onChanged(@Nullable MyRecommendOrderBean data) {
        loadData(true, data);
    }
}
